/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cliente;

import ServidorDistribuido.HiloServidorEscritura;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.rmi.*;
import ServidorDistribuido.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.logging.Level;
import java.util.logging.Logger;

public class EjecutorClass implements InterfazRemota  {

    String workingDirectory;
    final String INPUTFOLDER = "/ArchivosClass/";
    final String OUTPUTFOLDER = "/Resultados/";
    InetAddress address;
    Socket socket;
    
    public EjecutorClass(InetAddress address,Socket socket) throws RemoteException {
        super();
        this.address = address;
        this.socket = socket;
        workingDirectory= System.getProperty("user.dir");
    }

    public void recibirClass(Caja caja) throws RemoteException {
        
        HiloServidorEscritura.enviarEstadoEjecucion(socket, address, true);
        System.out.println("Cliente.Ejecutor.class. length de caja" + caja.getData().length);
        try{
            String nombreArchivo = caja.getName().split("\\.")[0] +".txt";
            
            FileOutputStream aux = new FileOutputStream(workingDirectory+ INPUTFOLDER + caja.getName());
            
            caja.writeTo(aux);
            aux.flush();
            aux.close();
            System.out.println("java -classpath" + workingDirectory + INPUTFOLDER + " " + caja.getName().split("\\.")[0]);
            
            Process p = Runtime.getRuntime().exec ("java -classpath " + workingDirectory + INPUTFOLDER +  " " + caja.getName().split("\\.")[0]);
                  
            
            File f=new File(workingDirectory + OUTPUTFOLDER  + caja.getName().split("\\.")[0] +".txt");
            InputStream inputStream= p.getInputStream();
            OutputStream out= new FileOutputStream(f);
            byte buf[]=new byte[1024];
            int len;
            while((len=inputStream.read(buf))>0)
                out.write(buf,0,len);
            out.close();
            inputStream.close();
            
        HiloServidorEscritura.enviarEstadoEjecucion(socket, address, false);
        HiloServidorEscritura.enviarArchivosPorServidor(socket, nombreArchivo, Servidor.relojLogico, address);
            
        }catch( IOException e ){
            e.printStackTrace();
        }
    }
   
    

    public Caja buscarResultado(String nombreArchivo) throws RemoteException {
        Caja caja = new Caja(workingDirectory + OUTPUTFOLDER  + nombreArchivo +".txt");
        caja.readIn();
        return caja;
    }
 }      